// V-backend/src/controllers/activityController.js
const { Activity, Registration, Anchor, Audience } = require('../models');

// 获取活动列表
exports.getActivities = async (req, res) => {
  try {
    console.log('🎯 收到获取活动列表请求，查询参数:', req.query);
    
    const { page = 1, limit = 10, status, anchor_id } = req.query;
    const offset = (page - 1) * limit;
    
    const where = {};
    if (status) where.status = status;
    if (anchor_id) where.anchor_id = anchor_id;
    
    console.log('📝 查询条件:', where);
    
    // 先测试简单查询
    console.log('🔍 测试简单查询...');
    const testActivities = await Activity.findAll({ 
      limit: 2,
      raw: true 
    });
    console.log('✅ 简单查询结果:', testActivities);
    
    // 完整查询
    const activities = await Activity.findAndCountAll({
      where,
      include: [{
        model: Anchor,
        as: 'anchor',
        attributes: ['anchor_id', 'anchor_name', 'avatar']
      }],
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });
    
    console.log('✅ 完整查询结果:', {
      查询到记录数: activities.count,
      返回记录数: activities.rows.length
    });
    
    // 格式化返回数据
    const formattedActivities = activities.rows.map(activity => {
      const activityData = activity.get ? activity.get({ plain: true }) : activity;
      
      return {
        id: activityData.activity_id,
        activity_id: activityData.activity_id,
        anchor_id: activityData.anchor_id,
        title: activityData.title,
        description: activityData.description,
        cover_image: activityData.cover_image,
        start_time: activityData.start_time,
        end_time: activityData.end_time,
        location: activityData.location,
        status: activityData.status,
        max_participants: activityData.max_participants,
        current_participants: activityData.current_participants,
        tags: activityData.tags,
        created_at: activityData.created_at,
        anchor: activityData.anchor || null
      };
    });
    
    res.json({
      success: true,
      data: formattedActivities,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: activities.count,
        totalPages: Math.ceil(activities.count / limit)
      }
    });
    
  } catch (error) {
    console.error('❌ 获取活动列表详细错误:');
    console.error('错误信息:', error.message);
    console.error('错误堆栈:', error.stack);
    console.error('错误名称:', error.name);
    
    res.status(500).json({
      success: false,
      message: '获取活动列表失败',
      error: error.message,
      stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
    });
  }
};

// 获取活动详情
exports.getActivityById = async (req, res) => {
  try {
    const { id } = req.params;
    console.log('🎯 获取活动详情，ID:', id);
    
    const activity = await Activity.findByPk(id, {
      include: [{
        model: Anchor,
        as: 'anchor',
        attributes: ['anchor_id', 'anchor_name', 'avatar', 'anchor_info']
      }]
    });
    
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }
    
    const activityData = activity.get ? activity.get({ plain: true }) : activity;
    
    // 格式化返回数据
    const formattedActivity = {
      id: activityData.activity_id,
      activity_id: activityData.activity_id,
      anchor_id: activityData.anchor_id,
      title: activityData.title,
      description: activityData.description,
      cover_image: activityData.cover_image,
      start_time: activityData.start_time,
      end_time: activityData.end_time,
      location: activityData.location,
      status: activityData.status,
      max_participants: activityData.max_participants,
      current_participants: activityData.current_participants,
      tags: activityData.tags,
      created_at: activityData.created_at,
      anchor: activityData.anchor || null,
      isRegistered: false
    };
    
    res.json({
      success: true,
      data: formattedActivity
    });
  } catch (error) {
    console.error('获取活动详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取活动详情失败',
      error: error.message
    });
  }
};

// 创建活动 (策划方)
exports.createActivity = async (req, res) => {
  try {
    const activityData = {
      ...req.body,
      anchor_id: req.user.anchor_id // 从token中获取
    };
    
    const activity = await Activity.create(activityData);
    
    res.status(201).json({
      success: true,
      message: '活动创建成功',
      data: activity
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '创建活动失败',
      error: error.message
    });
  }
};

// 更新活动
exports.updateActivity = async (req, res) => {
  try {
    const { id } = req.params;
    
    const activity = await Activity.findByPk(id);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }
    
    // 检查权限
    if (activity.anchor_id !== req.user.anchor_id) {
      return res.status(403).json({
        success: false,
        message: '无权修改此活动'
      });
    }
    
    await activity.update(req.body);
    
    res.json({
      success: true,
      message: '活动更新成功',
      data: activity
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新活动失败',
      error: error.message
    });
  }
};

// 预约活动
exports.registerActivity = async (req, res) => {
  try {
    console.log('🔍 JWT用户信息:', req.user); // 添加调试信息
    
    const { activity_id } = req.body;
    
    // 检查 audience_id 是否存在
    if (!req.user || !req.user.userId) {
      return res.status(401).json({
        success: false,
        message: '用户身份验证失败'
      });
    }
    
    const audience_id = req.user.userId; // 使用 userId 而不是 audience_id
    
    console.log('📝 预约参数:', { audience_id, activity_id });

    // 检查活动是否存在
    const activity = await Activity.findByPk(activity_id);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }

    // 检查活动状态 - 根据你的数据库状态值调整
    if (activity.status !== 'published') {
      return res.status(400).json({
        success: false,
        message: '活动不可预约'
      });
    }

    // 检查是否已预约
    const existingRegistration = await Registration.findOne({
      where: { audience_id, activity_id }
    });
    
    if (existingRegistration) {
      return res.status(400).json({
        success: false,
        message: '您已预约此活动'
      });
    }

    // 检查人数限制
    if (activity.max_participants && activity.current_participants >= activity.max_participants) {
      return res.status(400).json({
        success: false,
        message: '活动人数已满'
      });
    }

    // 创建预约
    const registration = await Registration.create({
      audience_id,
      activity_id,
      status: 'registered'
    });

    // 更新活动参与人数
    await activity.update({
      current_participants: activity.current_participants + 1
    });

    res.status(201).json({
      success: true,
      message: '预约成功',
      data: registration
    });
  } catch (error) {
    console.error('❌ 预约失败:', error);
    res.status(500).json({
      success: false,
      message: '预约失败',
      error: error.message
    });
  }
};

// 取消预约
exports.cancelRegistration = async (req, res) => {
  try {
    if (!req.user || !req.user.userId) {
      return res.status(401).json({
        success: false,
        message: '用户身份验证失败'
      });
    }
    
    const { activity_id } = req.params;
    const audience_id = req.user.userId; // 使用 userId
    
    const registration = await Registration.findOne({
      where: { audience_id, activity_id }
    });
    
    if (!registration) {
      return res.status(404).json({
        success: false,
        message: '未找到预约记录'
      });
    }
    
    await registration.update({ status: 'cancelled' });
    
    // 更新活动参与人数
    const activity = await Activity.findByPk(activity_id);
    if (activity) {
      await activity.update({
        current_participants: Math.max(0, activity.current_participants - 1)
      });
    }
    
    res.json({
      success: true,
      message: '取消预约成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '取消预约失败',
      error: error.message
    });
  }
};

// 获取用户的预约列表
exports.getUserRegistrations = async (req, res) => {
  try {
    if (!req.user || !req.user.userId) {
      return res.status(401).json({
        success: false,
        message: '用户身份验证失败'
      });
    }
    
    const audience_id = req.user.userId; // 使用 userId
    const { page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;
    
    const registrations = await Registration.findAndCountAll({
      where: { audience_id },
      include: [{
        model: Activity,
        as: 'activity',
        include: [{
          model: Anchor,
          as: 'anchor'
        }]
      }],
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['registration_time', 'DESC']]
    });
    
    res.json({
      success: true,
      data: registrations.rows,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: registrations.count,
        totalPages: Math.ceil(registrations.count / limit)
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取预约列表失败',
      error: error.message
    });
  }
};